<template>
  <view class="w100 pb-20">
    <uni-card padding="0">
      <view class="inforClass pt-20">报告内容</view>
      <view class="w100 rowsb rowsm pt-20">
        <view class="w100 rowsb rowsm h100 border-botm pb-20">
          <view class="fs-28 col333 fw-b">实践任务名称：{{ info.taskName }}</view>
        </view>
      </view>
      <view class="w100 rowsb rowsm h100 border-botm pt-20 pb-20" v-if="info.status == 4">
        <view class="fs-28 col333 fw-b"><text style="color: red">*</text>实践报告名称：</view>
        <input type="text" placeholder="请输入实践报告名称" style="flex: 1"
          :style="{ 'color': info.projectName !== null ? '#000' : '#a9a9a9' }" v-model="info.projectName">
      </view>
      <view class="w100 rowsb rowsm border-botm pt-20 pb-20" v-else>
        <view class="fs-28 col333 fw-b">实践项目名称：</view>
        <view>{{ info.projectName }}</view>
      </view>
      <view class="w100 rowsb rowsm border-botm p-all-10" v-if="itemData.isSubmit == '已完成'">
        <view class="fs-28 col333 fw-b">获得积分：</view>
        <view>{{ info.grade }}</view>
      </view>
      <view v-if="info.status == 4" class="w100 rowsb rowsm h100 border-botm pt-20 pb-20">
        <view class="w100 rowsb rowsm h100" @tap="show = true">
          <view class="fs-28 col333 fw-b"><text style="color: red">*</text>实践开始时间：</view>
          <view v-if="startTime">{{ startTime }}</view>
          <view v-else class="fs-28 col888">请选择实践开始时间</view>
        </view>
      </view>
      <view class="w100 rowsb rowsm border-botm pt-20 pb-20" v-else>
        <view class="fs-28 col333 fw-b">实践开始时间：</view>
        <view>{{ (info.practiceStartTime || '').slice(0, 16) }}</view>
      </view>
      <u-datetime-picker :show="show" mode="datetime" v-model="value1" @confirm="confirmStartTime"
        @cancel="show = false"></u-datetime-picker>
      <view v-if="info.status == 4" class="w100 rowsb rowsm h100 border-botm pt-20 pb-20">
        <view class="w100 rowsb rowsm h100" @tap="endTimeShow = true">
          <view class="fs-28 col333 fw-b"><text style="color: red">*</text>实践结束时间：</view>
          <view v-if="endTime">{{ endTime }}</view>
          <view v-else class="fs-28 col888">请选择实践结束时间</view>
        </view>
      </view>
      <view class="w100 rowsb rowsm border-botm pt-20 pb-20" v-else>
        <view class="fs-28 col333 fw-b">实践结束时间：</view>
        <view>{{ (info.practiceEndTime || '').slice(0, 16) }}</view>
      </view>
      <u-datetime-picker :show="endTimeShow" mode="datetime" v-model="value1" @confirm="confirmEndTime"
        @cancel="endTimeShow = false"></u-datetime-picker>

      <view class="w100 rowsb rowsm h100 border-botm pt-20 pb-20" v-if="info.status == 4">
        <view class="fs-28 col333 fw-b"><text style="color: red">*</text>实践报告地点：</view>
        <input type="text" placeholder="请输入实践报告地点" style="flex: 1"
          :style="{ 'color': info.practicePlace !== null ? '#000' : '#a9a9a9' }" v-model="info.practicePlace">
      </view>
      <view class="w100 rowsb rowsm border-botm pt-20 pb-20" v-else>
        <view class="fs-28 col333 fw-b">实践报告地点：</view>
        <view>{{ info.practicePlace }}</view>
      </view>
    </uni-card>

    <uni-card padding="0">
      <view class="inforClass pt-20">实践详细说明</view>
      <textarea v-if="info.status == 4" style="width: 100%" placeholder="请输入您的实践说明"
        :style="{ 'color': info.detail !== null ? '#000' : '#a9a9a9' }" v-model="info.detail" />
      <view v-else class="pt-10 pb-20" style="width: 100%; color: #000;">{{ info.detail }}</view>
    </uni-card>

    <uni-card padding="0" v-if="info.status == 4 || (info.status != 4 && fileList.length != 0)">
      <view class="inforClass pt-20">填报附件</view>
      <view class="w100 pl-12 pr-12 mb-20" v-if="info.status == 4">
        <view class="w100 h-120 br-10 rows rowsm pl-20 mb-10" style="background-color: #F7F6FA;" @click="choseFile"
          v-if="info.status == 4">
          <image src="/static/icon_cs.png" class="w-50 h-60 mr-20" mode=""></image>
          <!-- <view class="fs-26 col888">（可上传word、pdf、excel、图片、视频）</view> -->
          <view class="fs-26 col888">
            <view class="fs-24">须知: 图片最多6张、文件最多1个最大10M、视频最多1个最大100M,且附件为必填项</view>
            <view>（可上传word、pdf、图片、视频）</view>
          </view>
        </view>
        <view>
          <view class="w100 h-140 br-10 rowsb rowsm pl-20" style="background-color: #F7F6FA;"
            v-for="(item, index) in fileList" :key="index">
            <view class="rows rowsm w-300" @click="openFile(item)">
              <image src="/static/file.png" class="w-60 h-60 mr-20" mode=""></image>
              <view class="fs-28 col888 w100 one_overflow">{{ item.fileName }}</view>
            </view>
            <view class="w-120 h-60 br-30 rowsc rowsm colfff fs-24 mr-20"
              style="background: linear-gradient(to bottom,#4897FF,#4878FF);" @click="handelDelete(item)"
              v-if="info.status == 4">删除</view>
          </view>
        </view>
      </view>

      <view v-else>
        <view v-for="item in fileList" :key="item.id">
          <image :src="item.fileSrc" class="w-200 h-200 br-20"
            v-if="item.fileType == 'png' || item.fileType == 'jpg' || item.fileType == 'jpeg' || item.fileType == 'able' || item.fileType == '图片'"
            mode="aspectFill" @click="openImg(item.fileSrc)">
          </image>
          <video id="myVideo" :src="item.fileSrc" class="w-200 h-200 br-20"
            v-if="item.fileType == 'mp4' || item.fileType == 'avi' || item.fileType == '视频'"
            @click="openVideo(item.fileSrc)"></video>
          <view class="w100 h-140 br-10 rows rowsm pl-40 mb-12" style="background-color: #F7F6FA;"
            v-if="item.fileType != 'png' && item.fileType != 'jpg' && item.fileType != 'jpeg' && item.fileType != 'able' && item.fileType != 'mp4' && item.fileType != 'avi' && item.fileType != '图片' && item.fileType != '视频'"
            @click="openFile(item)">
            <image src="/static/file.png" class="w-60 h-60 mr-20" mode=""></image>
            <view class="fs-28 col888 w100 one_overflow">{{ item.fileName }}</view>
          </view>
        </view>
      </view>
    </uni-card>

    <uni-card padding="0" v-if="info.status == 4 && info.reason">
      <view class="inforClass pt-20">驳回原因</view>
      <view class="pt-10 pb-20" style="width: 100%; color: #000;">{{ info.reason }}</view>
    </uni-card>


    <!-- 审核情况 -->
    <uni-card>
      <view class="w100 bgff br-10 mb-20">
        <view class="inforClass">审核情况:</view>
        <uni-section title="基本用法" type="line" padding>
          <uni-steps :options="list1" :active="active" />
        </uni-section>
      </view>
    </uni-card>

    <view class="w100 rowsa rowsm p-all-20" v-if="info.status == 4">
      <view class="w-702 h-84 br-42 rowsc rowsm colfff" style="background: linear-gradient(to bottom,#4897FF,#4878FF);"
        @click="submit()">提交
      </view>
    </view>
  </view>
</template>

<script>
import axios from 'axios';
export default {
  data() {
    return {
      show: false,
      endTimeShow: false,
      startTime: '',
      endTime: '',
      value1: Number(new Date()),
      fileList: [],
      info: {},
      itemData: {},
      active: 1,
      list1: [],
    };
  },
  onLoad(e) {

    uni.setNavigationBarTitle({
      title: e.title + '详情'
    })
    this.$tools.axiosFromToken('get', `practice/user/${e.id}`, {}, '加载中').then(res => {
      if (res.code != 200) return this.$tools.showtt(res.msg)
      this.info = { ...res.data }
      this.startTime = (this.info.practiceStartTime || '').slice(0, 16);
      this.endTime = (this.info.practiceEndTime || '').slice(0, 16);
      this.info.studentFileList.forEach((file, fileIndex) => {
        this.fileList.push({ ...file })
      })
      if (this.fileList.length === res.data.studentFileList.length && res.data.studentFileList.length != 0) {

        this.getImg();
      }
      const timeFields = [
        { key: 'createTime', title: '提交时间', activeValue: 0 },
        { key: 'collegeCheckTime', title: this.info.status == 4 && !this.info.schoolCheckTime ? '驳回时间' : '审核时间', activeValue: 1 },
      ];
      timeFields.forEach(field => {
        if (this.info[field.key]) {
          this.active = field.activeValue;
          this.list1.push({ title: field.title,desc: this.info[field.key] + (field.title != '提交时间' ? '\n审核人: ' + (this.info.collegeCheckName || '') : '') });
        }
      });
    })
  },
  methods: {
    getImg() {
      if (this.info.status != 4) {
        this.$nextTick(() => {
          this.fileList.forEach((item, fileIndex) => {
            this.fetchImage(item.file, fileIndex)
          });
        })
      }
    },
    async fetchImage(urls, index) {
      const that = this;
      try {
        const response = await axios.get(this.$tools.avatarUrl + urls, {
          responseType: 'arraybuffer' // 获取二进制数据
        });
        const blob = new Blob([response.data], { type: 'image/jpeg' });
        const imageUrl = URL.createObjectURL(blob);
        that.fileList[index].fileSrc = imageUrl;
        that.$forceUpdate();
      } catch (error) {
        console.error('Failed to fetch image:', error);
      }
    },
    openImg(url) {
      let urlList = [];
      this.fileList.forEach(item => {
        if (item.fileType == 'jpg' || item.fileType == 'jpeg' || item.fileType == 'png' || item.fileType == 'gif' || item.fileType == 'able' || item.fileType == '图片') {
          urlList.push(item.fileSrc)
        }
      });
      uni.previewImage({
        current: url,
        urls: urlList,
        loop: false,
        indicator: 'number',
      });
    },
    openVideo(url) {
      var video = document.getElementById("myVideo");
      // 检查浏览器是否支持全屏 API
      if (video.requestFullscreen) {
        // 支持 requestFullscreen 的浏览器
        video.requestFullscreen();
      } else if (video.mozRequestFullScreen) {
        // Firefox 支持 mozRequestFullScreen
        video.mozRequestFullScreen();
      } else if (video.webkitRequestFullscreen) {
        // Chrome 和 Safari 支持 webkitRequestFullscreen
        video.webkitRequestFullscreen();
      } else if (video.msRequestFullscreen) {
        // Internet Explorer 支持 msRequestFullscreen
        video.msRequestFullscreen();
      }
    },
    hideKeyboard() {
      uni.hideKeyboard();
    },
    openFile(url) {
      const userAgent = navigator.userAgent.toLowerCase();
      if (userAgent.match(/MicroMessenger/i)) {
        const fileUrl = this.$tools.avatarUrl + url.file;
        window.open(fileUrl, '_blank');
      } else if (userAgent.match(/wxwork/i)) {
        const fileUrl = this.$tools.avatarUrl + url.file;
        window.open(fileUrl, '_blank');
      } else {
        const fileUrl = this.$tools.avatarUrl + url.file;
        fetch(fileUrl)
          .then(response => response.blob())
          .then(blob => {
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.download = url.fileName; // 指定下载文件的默认名称
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(link.href); // 释放对象 URL
          })
          .catch(error => {
            console.error("下载失败：", error);
          });
      }
      // uni.downloadFile({
      //   url: this.$tools.avatarUrl + url,
      //   success(res) {
      //     // 获取文件路径
      //     const filePath = res.tempFilePath;
      //     // 在 H5 中，使用浏览器打开文件
      //     uni.openDocument({
      //       filePath: res.tempFilePath,
      //       showMenu: true,
      //       complete(msg) {
      //         window.open(filePath, '_blank');
      //       }
      //     })
      //   }
      // })
    },
    choseFile() {
      // if (this.fileList.length === 5) return this.$tools.showtt('最多上传5个文件');
      let currentTotalSize = this.fileList.reduce((acc, item) => {
        return acc + item.size;
      }, 0);
      // const type = this.taskType == '劳动教育' ? 'ldjy' : this.taskType == '职业素养' ? 'zysj' : this.taskType == '应急安全' ? 'yjaqjy' : this.taskType == '思想实践教育' ? 'sxsjjy' : 'cxcyjy'
      uni.showActionSheet({
        itemList: ['图片', '文件', '视频'],
        success: (index, e) => {
          if (index.tapIndex === 0) {
            let imgNum = 0;
            this.fileList.forEach((itemImg) => {
              if (itemImg.fileType === '图片') {
                imgNum++;
              }
            });
            if (imgNum === 6) {
              this.$tools.showtt('最多可以只能上传6张图片');
              return
            }
            uni.chooseImage({
              count: 5 - this.fileList.length,
              sizeType: ['compressed'], // 选择压缩后的图片
              sourceType: ['album', 'camera'],
              success: (res) => {
                res.tempFilePaths.forEach(item => {
                  // this.compressImage(item).then((compressedFilePath) => {
                    uni.uploadFile({
                      url: this.$tools.httpOne + 'utils/ossUpload',
                      filePath: item,
                      name: 'file',
                      header: {
                        'Authorization': "Bearer " + sessionStorage.getItem('token')
                        // 'token': sessionStorage.getItem('token')
                      },
                      success: (res1) => {
                        if (JSON.parse(res1.data).code === 200) {
                          this.fileList.push({
                            fileName: JSON.parse(res1.data).originalFilename,
                            // fileType: JSON.parse(res1.data).originalFilename.split('.')[1],
                            fileType: '图片',
                            file: JSON.parse(res1.data).url,
                            // type: type,
                          });
                        } else {
                          this.$tools.showtt(JSON.parse(res1.data).msg);
                        }
                      }
                    // });
                  })
                  // 检查单个文件大小，6MB = 6 * 1024 * 1024
                  // if (res.tempFiles[0].size > 6 * 1024 * 1024) {
                  //   this.$tools.showtt('图片大小不能超过6MB');
                  //   return;
                  // }
                  // // 检查总文件大小
                  // currentTotalSize += res.tempFiles[0].size;
                  // if (currentTotalSize > 6 * 1024 * 1024) {
                  //   this.$tools.showtt('附件总大小不能超过6MB');
                  //   currentTotalSize -= res.tempFiles[0].size; // 回退当前大小
                  //   return;
                  // }
                });
              }
            });
          }
          if (index.tapIndex === 1) {
            if (this.fileList.find(v => v.fileType == '文件')) {
              this.$tools.showtt('最多只能上传一个文件');
              return
            }
            uni.chooseFile({
              count: 1,
              type: 'file',
              success: (res) => {
                uni.uploadFile({
                  url: this.$tools.httpOne + 'utils/ossUpload',
                  filePath: res.tempFilePaths[0],
                  header: {
                    'Authorization': "Bearer " + sessionStorage.getItem('token')
                    // 'token': sessionStorage.getItem('token')
                  },
                  name: 'file',
                  success: (res1) => {
                    const data = JSON.parse(res1.data);
                    if (data.code === 200) {
                      const fileExtension = data.originalFilename.split('.').pop().toLowerCase();
                      const allowedExtensions = ['txt', 'pdf', 'doc', 'docx', 'ppt', 'xlsx', 'xls']; // 允许的文件扩展名列表
                      if (allowedExtensions.includes(fileExtension)) {
                        this.fileList.push({
                          fileName: data.originalFilename,
                          // fileType: JSON.parse(res1.data).originalFilename.split('.')[1],
                          fileType: '文件',
                          file: data.url,
                          // type: type
                        });
                      } else {
                        this.$tools.showtt('上传文件仅支持txt、pdf、word、excel、ppt');
                      }
                    } else {
                      this.$tools.showtt(JSON.parse(res1.data).msg);
                    }
                  }
                });
              }
            });
          }
          function checkFileSize(fileSize, maxSize) {
            if (fileSize > maxSize) {
              uni.showToast({
                title: `文件大小不能超过 ${maxSize / 1024 / 1024}MB`,
                icon: 'none'
              });
              return false;
            }
            return true;
          }
          if (index.tapIndex === 2) {
            if (this.fileList.find(v => v.fileType == '视频')) {
              this.$tools.showtt('最多只能上传一个视频');
              return
            }
            uni.chooseVideo({
              sourceType: ['album', 'camera'],
              compressed: true, // 启用自动压缩
              maxFileSize: 60 * 1024 * 1024, // 最大文件大小，单位为字节，这里是10MB
              success: (res) => {
                // 检查文件大小是否超过50MB
                if (!checkFileSize(res.size, 60 * 1024 * 1024)) {
                  return;
                }
                uni.uploadFile({
                  url: this.$tools.httpOne + 'utils/ossUpload',
                  filePath: res.tempFilePath,
                  name: 'file',
                  header: {
                    'Authorization': "Bearer " + sessionStorage.getItem('token')
                    // 'token': sessionStorage.getItem('token')
                  },
                  success: (res1) => {
                    if (JSON.parse(res1.data).code === 200) {
                      this.fileList.push({
                        fileName: JSON.parse(res1.data).originalFilename,
                        // fileType: JSON.parse(res1.data).originalFilename.split('.')[1],
                        fileType: '视频',
                        file: JSON.parse(res1.data).url,
                        // type: type
                      });
                    } else {
                      this.$tools.showtt(JSON.parse(res1.data).msg);
                    }
                  }
                });
              }
            });
          }
        }
      });
    },
    // 图片压缩函数
    compressImage(filePath) {
      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: filePath,
          success: (imageInfo) => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            const img = new Image();

            img.onload = () => {
              const MAX_WIDTH = 800; // 最大宽度
              const MAX_HEIGHT = 800; // 最大高度
              let width = img.width;
              let height = img.height;

              if (width > height && width > MAX_WIDTH) {
                height = (height / width) * MAX_WIDTH;
                width = MAX_WIDTH;
              } else if (height > width && height > MAX_HEIGHT) {
                width = (width / height) * MAX_HEIGHT;
                height = MAX_HEIGHT;
              }

              canvas.width = width;
              canvas.height = height;
              ctx.drawImage(img, 0, 0, width, height);

              canvas.toBlob((blob) => {
                const newFilePath = URL.createObjectURL(blob);
                resolve(newFilePath);
              }, 'image/jpeg', 0.8); // 压缩质量
            };
            console.log(imageInfo.path);
            img.src = imageInfo.path;
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },
    // 劳动开始时间
    confirmStartTime(e) {
      if (this.info.practiceEndTime && new Date(this.info.practiceEndTime.replace(' ', 'T')).getTime() < e.value) {
        this.$tools.showtt('开始时间大于结束时间,请重新选择')
        return
      }
      this.info.practiceStartTime = e.value;
      const formattedDate = new Date(e.value).toLocaleString(); // 转为本地时间字符串
      this.startTime = formattedDate.split('/').join("-");
      this.show = false;

    },
    //  劳动结束时间
    confirmEndTime(e) {
      if (this.info.practiceStartTime && new Date(this.info.practiceStartTime.replace(' ', 'T')).getTime() > e.value) {
        this.$tools.showtt('结束时间小于开始时间,请重新选择')
        return
      }
      this.info.practiceEndTime = e.value;
      const formattedDate = new Date(e.value).toLocaleString(); // 转为本地时间字符串
      this.endTime = formattedDate.split('/').join("-");
      this.endTimeShow = false;
    },
    handelDelete(item) {
      this.fileList.splice(this.fileList.findIndex(v => v.fileName === item.fileName), 1)
    },
    submit() {
      if (!this.info.projectName) return this.$tools.showtt('请输入项目')
      if (!this.info.practiceStartTime) return this.$tools.showtt('请选择开始时间')
      if (!this.info.practiceEndTime) return this.$tools.showtt('请选择结束时间')
      if (!this.info.practicePlace) return this.$tools.showtt('请输入地点')
      if (!this.info.detail) return this.$tools.showtt('请输入详情说明')
      if (this.fileList.length == 0) return this.$tools.showtt('附件不得为空')
      let data = { ...this.info, studentFileList: this.fileList }
      this.$tools.axiosFromToken('POST', 'practice/user/edit', { ...data, status: 1 }, '加载中').then(res => {
        this.$tools.showtt(res.msg)
        if (res.code != 200) return
        setTimeout(() => {
          this.$tools.goBack(1)
        }, 1000)
      })
    }
  }
}
</script>

<style lang="scss">
page {
  background-color: #f4f5f7;
}

.ellipsis-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  display: inline-block;
  align-items: center;
}

::v-deep .uni-card__content {
  color: #000 !important;
}

.inforClass {
  font-size: 16px;
  font-weight: 700;
  display: flex;
  align-items: center;
  margin: 8px 0;
}

.inforClass::before {
  content: '';
  width: 5px;
  height: 20px;
  background-color: #007AFF;
  margin-right: 5px;
  display: inline-block;
}

.mark {
  text-align: right;
  color: #f92929;
}

.btn {
  font-size: 26rpx;
  border: 1px solid #5ac725;
  padding: 5px 10px;
  border-radius: 20px;
  color: #5ac725;
  background: #fff;
}

.border-botm {
  border-bottom: 1px #f1f1f1 solid;
}
</style>
